package top.kaoshanji.ch04;

import com.google.common.io.Resources;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.ch04.client.MoreBodyPublishers;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import java.util.Properties;

/**
 * 代码清单 ch04-07：HttpClient示例(4.4节)
 * 提供了用于表单数据和文件上传的体发布器
 * author kaoshanji
 * ^_^
 * create time 2024/12/8 11:31
 */
public class HttpClientTest {

    private static final Logger logger = LogManager.getLogger(HttpClientTest.class);

    // 加载的文件决定了提交什么数据
    // 目前可以执行的是 post、json
    static final String FILE_NAME = "ch04/client/post.properties";

    public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException {
        logger.info("...代码清单 ch04-07：HttpClient示例(4.4节)...");

        URL urlFile = Resources.getResource(FILE_NAME);
        var props = new Properties();
        props.load(urlFile.openStream());

        String urlString = "" + props.remove("url");
        String contentType = "" + props.remove("Content-Type");
        /*if (contentType.equals("multipart/form-data")) { // 文件上传的先跳过..
            var generator = new Random();
            String boundary = new BigInteger(256, generator).toString();
            contentType += ";boundary=" + boundary;
            props.replaceAll((k, v) ->
                    v.toString().startsWith("file://") );

        }*/

        // 具体的提交逻辑
        String result = doPost(urlString, contentType, props);
        System.out.println(result);
    }

    public static String doPost(String url, String contentType, Map<Object, Object> data) throws URISyntaxException, IOException, InterruptedException {

        // 构件 HttpClient
        HttpClient client = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build();

        HttpRequest.BodyPublisher publisher = null;
        if (contentType.startsWith("multipart/form-data")) { // 文件上传的体发布器
            String boundary = contentType.substring(contentType.lastIndexOf("=") + 1);
            publisher = MoreBodyPublishers.ofMimeMultiparData(data, boundary);
        } else if (contentType.equals("application/x-www-form-urlencoded")) { // 表单的体发布器
            publisher = MoreBodyPublishers.ofFormData(data);
        } else {
            contentType = "application/json"; // JSON的体发布器
            publisher = MoreBodyPublishers.ofSimpleJSON(data);
        }

        // 请求体
        HttpRequest request = HttpRequest.newBuilder()
                .uri(new URI(url))
                .header("Content-Type", contentType)
                .POST(publisher)
                .build();

        // 发送响应
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        return response.body();
    }


}
